package at.fhooe.mcm.lri.mdmpoc.warehouse.dao.jdo;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;

import at.fhooe.mcm.lri.mdmpoc.warehouse.dao.PMF;
import at.fhooe.mcm.lri.mdmpoc.warehouse.dao.PersonDao;
import at.fhooe.mcm.lri.mdmpoc.warehouse.datamodel.Person;



@SuppressWarnings("unchecked")
public class PersonJdoDao implements PersonDao {
	private static final PersistenceManagerFactory pmf = PMF.getFactory();

	private void getResults(Collection<Person> persons, Object queryResult) {
		for (Person p : (Collection<Person>) queryResult) {
			persons.add(p);
		}
	}
	@Override
	public Collection<Person> findAll() {
		List<Person> persons = new ArrayList<Person>();
		PersistenceManager pm = pmf.getPersistenceManager();
		try {
			Query query = pm.newQuery(Person.class);
			getResults(persons, query.execute());
		} finally {
			pm.close();
		}
		return persons;
	}

	@Override
	public Person findById(Long key) {
		Person p = null;

		PersistenceManager pm = pmf.getPersistenceManager();
		try {
			p = pm.getObjectById(Person.class, key);
		} finally {
			pm.close();
		}
		return p;
	}

	@Override
	public void insertPerson(Person p) {
		PersistenceManager pm = pmf.getPersistenceManager();
		try {
			pm.makePersistent(p);
		} finally {
			pm.close();
		}
	}
	@Override
	public Person updatePerson(Person person) {
		Person p = null;

		PersistenceManager pm = pmf.getPersistenceManager();
		try {
			pm.currentTransaction().begin();

			p = pm.getObjectById(Person.class, person.getKey());
			p.setName(person.getName());
			p.setBiography(person.getBiography());
			pm.makePersistent(p);

			pm.currentTransaction().commit();
		} catch (RuntimeException ex) {
			pm.currentTransaction().rollback();
			throw ex;
		} finally {
			pm.close();
		}
		return p;
	}
	@Override
	public void deletePerson(Person person) {
		Person p = null;

		PersistenceManager pm = pmf.getPersistenceManager();
		try {
			pm.currentTransaction().begin();
			p = pm.getObjectById(Person.class, person.getKey());
			if (p != null)
				pm.deletePersistent(p);
			pm.currentTransaction().commit();
		} catch (RuntimeException ex) {
			pm.currentTransaction().rollback();
			throw ex;
		} finally {
			pm.close();
		}
	}
}
